package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.dto.ScanRentalDTO;
import com.powerbank.user.dto.ScanReturnDTO;
import com.powerbank.user.service.RentalService;
import com.powerbank.user.vo.RentalOrderVO;
import com.powerbank.user.vo.BillingInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

/**
 * 租借控制器
 */
@Slf4j
@RestController
@RequestMapping("/rental")
public class RentalController {

    @Autowired
    private RentalService rentalService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 扫码租借
     */
    @PostMapping("/scan")
    public Result<RentalOrderVO> scanRental(@RequestBody @Valid ScanRentalDTO rentalDTO,
                                            HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RentalOrderVO orderVO = rentalService.scanRental(userId, rentalDTO);
        return Result.success("租借申请成功，请完成支付", orderVO);
    }

    /**
     * 获取当前租借订单
     */
    @GetMapping("/current")
    public Result<RentalOrderVO> getCurrentRentalOrder(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RentalOrderVO orderVO = rentalService.getCurrentRentalOrder(userId);
        return Result.success(orderVO);
    }

    /**
     * 确认支付
     */
    @PostMapping("/confirm-payment/{orderId}")
    public Result<RentalOrderVO> confirmPayment(@PathVariable Long orderId,
                                                HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RentalOrderVO orderVO = rentalService.confirmPayment(userId, orderId);
        return Result.success("支付成功，设备已开锁", orderVO);
    }

    /**
     * 取消租借
     */
    @PostMapping("/cancel/{orderId}")
    public Result<Void> cancelRental(@PathVariable Long orderId,
                                     HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        boolean success = rentalService.cancelRental(userId, orderId);
        return success ? Result.success("租借已取消", (Void) null) : Result.error("取消失败");
    }

    /**
     * 扫码归还
     */
    @PostMapping("/return/scan")
    public Result<RentalOrderVO> scanReturn(@RequestBody @Valid ScanReturnDTO returnDTO,
                                            HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RentalOrderVO orderVO = rentalService.scanReturn(userId, returnDTO);
        return Result.success("归还成功，请检查费用信息", orderVO);
    }

    /**
     * 获取归还费用预览
     */
    @GetMapping("/return/billing-preview/{orderId}")
    public Result<BillingInfoVO> getReturnBillingPreview(@PathVariable Long orderId,
                                                         HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        BillingInfoVO billingInfo = rentalService.getReturnBillingPreview(userId, orderId);
        return Result.success(billingInfo);
    }

    /**
     * 确认归还和费用结算
     */
    @PostMapping("/return/confirm/{orderId}")
    public Result<RentalOrderVO> confirmReturn(@PathVariable Long orderId,
                                               HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RentalOrderVO orderVO = rentalService.confirmReturn(userId, orderId);
        return Result.success("归还完成，费用已结算", orderVO);
    }

    /**
     * 上报设备故障
     */
    @PostMapping("/report-fault")
    public Result<Void> reportDeviceFault(@RequestParam String deviceCode,
                                         @RequestParam String faultType,
                                         @RequestParam String faultDescription,
                                         HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        try {
            boolean success = rentalService.reportDeviceFault(userId, deviceCode, faultType, faultDescription);
            return success ? Result.success("故障上报成功", (Void) null) : Result.error("故障上报失败");
        } catch (Exception e) {
            log.error("上报设备故障失败：{}", e.getMessage(), e);
            return Result.error("上报设备故障失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}